import com.sun.org.apache.xml.internal.dtm.ref.sax2dtm.SAX2DTM2;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author fangkun
 * @create 2022-11-08-14:26
 */
public class CreatingStreams {
    public static void main(String[] args) throws IOException {
        //读取文件内容
        Path path = Paths.get("D:\\test.txt");
        String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);

        //Stream.of方式创建流
        Stream<String> words = Stream.of(contents.split("\\PL+"));
        show("words",words);
        //可变长参数
        Stream<String> stream = Stream.of("a", "b", "c", "d");
        show("stream",stream);
        //空流
        Stream<Object> empty = Stream.empty();
        show("empty",empty);
        //Stream.generate方法
        Stream<Double> randoms = Stream.generate(Math::random);
        show("randoms",randoms);
        //1-10
        Stream<BigInteger> iterate = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE));
        show("iterate",iterate);
        //Pattern
        Stream<String> stringStream = Pattern.compile("\\PL+").splitAsStream(contents);
        show("stringStream",stringStream);
        //流元素为：文件中的行
        try(Stream<String> lines = Files.lines(path,StandardCharsets.UTF_8)){
            show("lines",lines);
        }
    }

    //打印方法
    public static <T> void show(String title, Stream<T>stream){
        final int SZIE = 10;
        List<T> firstElements = stream.limit(SZIE + 1).collect(Collectors.toList());
        System.out.println(title + ":");

        for (int i = 0; i < firstElements.size(); i++) {
            if (i>0) System.out.print(", ");
            if (i<SZIE) System.out.print(firstElements.get(i));
            else System.out.print("...");
        }
        System.out.println();
    }
}
